//
//  KKPhotoListViewController.m
//  KKImagePickerController
//
//  Created by Leo on 15/6/24.
//  Copyright (c) 2015年 Juvid. All rights reserved.
//

#import "KKPhotoListViewController.h"

#import "KKPhotoPreViewController.h"
#import "KKImagePickerModel.h"

static NSString* KKPhotoListItemCollectionCellIdentifier = @"KKPhotoListItemCollectionCellIdentifier";

@interface KKPhotoListViewController () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout> {
    
    UICollectionView* _collectionView;
    UIButton* _cancelButton;
    
    UIButton* _previewItem;
    UIButton* _sendButton;
    
    CGSize _itemCellSize;
    NSMutableArray* _assetsArray;
    NSMutableArray* _selectedAssetsArray;
}

@end

@implementation KKPhotoListViewController

- (void)loadView {
    [super loadView];
    UIView* rootView = [self view];
    rootView.backgroundColor = [UIColor whiteColor];
    
    KKPhotoListItemCellFlowLayout* flowLayout = [KKPhotoListItemCellFlowLayout new];
    
    _collectionView = [[UICollectionView alloc] initWithFrame: [rootView bounds] collectionViewLayout: flowLayout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [rootView addSubview: _collectionView];
    
    [_collectionView registerClass: [KKPhotoListItemCell class] forCellWithReuseIdentifier: KKPhotoListItemCollectionCellIdentifier];
    
    {
        _cancelButton = [UIButton buttonWithType: UIButtonTypeCustom];
        _cancelButton.frame = CGRectMake(0, 0, 40, 40);
        _cancelButton.titleLabel.font = [UIFont systemFontOfSize: 16.0];
        [_cancelButton setTitle: @"取消" forState: UIControlStateNormal];
        [_cancelButton setTitleColor: [UIColor blackColor] forState: UIControlStateNormal];
        [_cancelButton setTitleColor: [UIColor lightGrayColor] forState: UIControlStateHighlighted];
        [_cancelButton addGestureRecognizer: [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(onTap:)]];
        {
            UIBarButtonItem* rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView: _cancelButton];
            UIBarButtonItem* spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFixedSpace target: nil action: nil];
            spaceItem.width = -8;
            
            self.navigationItem.rightBarButtonItems = @[spaceItem,rightButtonItem];
        }
        
        _previewItem = [UIButton buttonWithType: UIButtonTypeCustom];
        _previewItem.frame = CGRectMake(0, 0, 40, 40);
        _previewItem.titleLabel.font = [UIFont systemFontOfSize: 16.0];
        [_previewItem setTitle: @"预览" forState: UIControlStateNormal];
        [_previewItem setTitleColor: [UIColor whiteColor] forState: UIControlStateNormal];
        [_previewItem setTitleColor: [UIColor lightGrayColor] forState: UIControlStateHighlighted];
        [_previewItem setTitleColor: [UIColor colorWithWhite: 1.0 alpha: 0.6] forState: UIControlStateDisabled];
        [_previewItem addGestureRecognizer: [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(onTap:)]];
        
        _sendButton = [UIButton buttonWithType: UIButtonTypeCustom];
        _sendButton.frame = CGRectMake(0, 0, 60, 40);
        _sendButton.titleLabel.font = [UIFont systemFontOfSize: 16.0];
        _sendButton.titleLabel.textAlignment = NSTextAlignmentRight;
        [_sendButton setTitleColor: [UIColor whiteColor] forState: UIControlStateNormal];
        [_sendButton setTitleColor: [UIColor lightGrayColor] forState: UIControlStateHighlighted];
        [_sendButton setTitleColor: [UIColor colorWithWhite: 1.0 alpha: 0.6] forState: UIControlStateDisabled];
        [_sendButton addGestureRecognizer: [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(onTap:)]];

        
        {
            UIBarButtonItem* previewItem = [[UIBarButtonItem alloc] initWithCustomView: _previewItem];
            UIBarButtonItem* sendItem = [[UIBarButtonItem alloc] initWithCustomView: _sendButton];
            
            UIBarButtonItem* spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target: nil action: nil];
            
            self.toolbarItems = @[previewItem,spaceItem, sendItem];
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    CGFloat width = CGRectGetWidth(_collectionView.bounds);
    CGFloat itemWidth = (width - 4 * 5) / 4.0;
    
    _itemCellSize = CGSizeMake(itemWidth, itemWidth);
    _assetsArray = [NSMutableArray array];
    
    NSInteger count = [[KKImagePickerModel sharedManager] count];
    [_sendButton setTitle: count == 0 ? @"保存" : [NSString stringWithFormat: @"保存(%@)", @(count)] forState: UIControlStateNormal];
    _previewItem.enabled = count;
    _sendButton.enabled = count;
    
    [self loadAssetsFromLibrary];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear: animated];
    
    [self.navigationController setToolbarHidden: NO animated: YES];
    
    [[KKImagePickerModel sharedManager] addObserver: self forKeyPath: @"count" options: NSKeyValueObservingOptionNew context: nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear: animated];
    
    [self.navigationController setToolbarHidden: YES animated: YES];
    
    [[KKImagePickerModel sharedManager] removeObserver: self forKeyPath: @"count"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    NSInteger count = [change[NSKeyValueChangeNewKey] integerValue];
    [_sendButton setTitle: count == 0 ? @"保存" : [NSString stringWithFormat: @"保存(%@)", @(count)] forState: UIControlStateNormal];
    _previewItem.enabled = count;
    _sendButton.enabled = count;
}

#pragma mark - UIGestureRecognizer methods

- (void)onTap:(UITapGestureRecognizer*)tapper {
    UIView* target = tapper.view;
    if (target == _cancelButton) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName: KKImagePickerControllerNotificationActionOfSend object: nil];
        return;
    }
    if (target == _previewItem) {
 
        KKPhotoPreViewController* preViewController = [KKPhotoPreViewController new];
        [self.navigationController pushViewController: preViewController animated: YES];
        return;
    }
    if (target == _sendButton) {
        
        NSDictionary* info = @{@"type":@"save"};
        [[NSNotificationCenter defaultCenter] postNotificationName: KKImagePickerControllerNotificationActionOfSend object: nil userInfo: info];
        return;
    }
}

#pragma mark - Private methods

- (void)loadAssetsFromLibrary {
    
    __weak NSMutableArray* weakAssets = _assetsArray;
    __weak UICollectionView* weakCollectionView = _collectionView;
    __weak ALAssetsGroup* weakGroup = _assetsGroup;
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        [weakGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
            
            if (result) {
                [weakAssets addObject: result];
            }
            else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakCollectionView reloadData];
                });
            }
        }];
    });
}

#pragma mark -
#pragma mark - UICollectionView methods

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _assetsArray.count;
}

- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    KKPhotoListItemCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier: KKPhotoListItemCollectionCellIdentifier forIndexPath: indexPath];
    
    ALAsset* assetItem = _assetsArray[indexPath.row];
    cell.itemImageView.image = [UIImage imageWithCGImage: assetItem.aspectRatioThumbnail];
    
    cell.choosed = [[KKImagePickerModel sharedManager] matchItem: assetItem];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    ALAsset* assetItem = _assetsArray[indexPath.row];
    
    KKImagePickerModel* pickerModel = [KKImagePickerModel sharedManager];
    
    if (![pickerModel matchItem: assetItem]) {
        [pickerModel addItemToArray: assetItem];
    }
    else {
        [pickerModel removeItemFromArray: assetItem];
    }
    [collectionView reloadItemsAtIndexPaths: @[indexPath]];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return _itemCellSize;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    
    return UIEdgeInsetsMake(4, 4, 4, 4);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 4.0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 4.0;
}

@end


#pragma mark -
#pragma mark -

@interface KKPhotoListItemCell() {
    
    UIImageView* _choosedImageView;
}

@end

@implementation KKPhotoListItemCell

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame: frame];
    if (self) {
        
        UIView* contentView = [self contentView];
        
        _itemImageView = [[UIImageView alloc] initWithFrame: [self bounds]];
        [contentView addSubview: _itemImageView];
        
        _choosedImageView = [[UIImageView alloc] initWithFrame: CGRectMake(CGRectGetWidth(contentView.bounds) - 28, 4, 24, 24)];
        
        NSString *imagePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"KKImagePickerController.bundle/Images/kk_item_seleted@2x.png"];
        
        _choosedImageView.image = [UIImage imageWithContentsOfFile: imagePath];
        _choosedImageView.hidden = YES;
        [contentView addSubview: _choosedImageView];
    }
    return self;
}

- (void)setChoosed:(BOOL)choosed {
    _choosed = choosed;
    
    _choosedImageView.hidden = !_choosed;
}

@end

#pragma mark - 
#pragma mark - 

@implementation KKPhotoListItemCellFlowLayout

- (id)init {
    self = [super init];
    if (self) {
        self.scrollDirection = UICollectionViewScrollDirectionVertical;
        self.minimumInteritemSpacing = 0.0f;
        self.minimumLineSpacing = 0.0f;
    }
    return self;
}

@end
